<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/8
 * Time: 15:11
 */

namespace app\admin\logic;


use app\common\utils\Constant;
use think\Db;
use think\Exception;

class SendLogic
{
    /**
     * 后台发送红包
     * @param $standard_id
     * @param $user_ids
     * @return array
     */
    public function sendRedEnvelope($standard_id,$user_ids){
        Db::startTrans();
        try{
            if(count($user_ids) == 0){
                return array('status'=>2,'msg'=>'请选择机器人');
            }
            $standard = model('Standard')->where(array('id'=>$standard_id))->find();
            if(!$standard){
                return array('status'=>2,'msg'=>'挑战规则不存在');
            }
            foreach ($user_ids as $key=>$user_id){
                $this->createRedEnvelope($standard,$user_id);
            }
            Db::commit();
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            return array('stats'=>0,'error'=>$e->getMessage());
        }
    }

    /**
     * 创建红包
     * @param $standard
     * @param $user_id
     * @return mixed
     */
    private function createRedEnvelope($standard,$user_id){
        $data['money'] = $standard['money'];
        $data['answer_money'] = $standard['answer_money'];
        $data['topic_number'] = $standard['topic_number'];
        $data['topic_grade'] = $standard['topic_grade'];
        $data['user_id'] = $user_id;
        $data['is_pay'] = 1;
        $data['status'] = Constant::RED_ENVELOPE_STATUS_NO_CHALLENGE;//未挑战
        $data['is_visible'] = 1;
        $data['create_time'] = time();
        $red_envelope = model('RedEnvelope')->create($data);
        return $red_envelope['id'];
    }

}